package com.yuzhenxin.coursesystem.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.framework.common.exception.ServiceException;
import com.example.framework.common.util.ExcelUtils;
import com.yuzhenxin.coursesystem.config.enums.ErrorCodeConstants;
import com.yuzhenxin.coursesystem.controller.admin.vo.UserQueryReqVO;
import com.yuzhenxin.coursesystem.entity.TeacherDO;
import com.yuzhenxin.coursesystem.mapper.TeacherMapper;
import com.yuzhenxin.coursesystem.service.TeacherService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, TeacherDO> implements TeacherService {

    @Resource
    private TeacherMapper teacherMapper;

    @Override
    public void insert(TeacherDO teacherEntity) {
        if (teacherMapper.selectById(teacherEntity.getId()) != null) {
            throw ServiceException.of(ErrorCodeConstants.USER_EXISTS);
        }
        teacherMapper.insert(teacherEntity);
    }

    // 获取所有教师信息
    @Override
    @Cacheable(value = "teachers", keyGenerator = "keyGenerator")
    public List<TeacherDO> selectList() {
        return teacherMapper.selectList(null);
    }

    @Override
    public IPage<TeacherDO> selectPage(UserQueryReqVO queryDto) {
        Page<TeacherDO> page = new Page<>(queryDto.getPageNo(), queryDto.getPageSize());
        Integer teacherId = queryDto.getNumber();
        String teacherName = queryDto.getName();
        LambdaQueryWrapper<TeacherDO> queryWrapper = Wrappers.<TeacherDO>lambdaQuery()
                .like(ObjectUtil.isNotEmpty(teacherId), TeacherDO::getNumber, teacherId)
                .like(ObjectUtil.isNotEmpty(teacherName), TeacherDO::getName, teacherName);
        return teacherMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Map<String, Object> selectCount() {
        return teacherMapper.teacherCounts();
    }

    @Override
    public List<Map<String, Object>> selectTeacherOrderByTpt() {
        return teacherMapper.selectTeacherOrderByTpt();
    }

    @Override
    public void exportData(HttpServletResponse response) {
        String fileName = "Teacher";
        List<TeacherDO> teacherEntityList = teacherMapper.selectList(null);
        ExcelUtils.export(fileName, "Teacher", teacherEntityList, TeacherDO.class, response);
    }
}
